package com.ztjava.portal.controller;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.aop.Before;
import com.jfinal.aop.Duang;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Ret;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.upload.UploadFile;
import com.ztjava.core.Constant;
import com.ztjava.core.InitConfig;
import com.ztjava.core.annotation.BackMethod;
import com.ztjava.core.base.BaseController;
import com.ztjava.core.log.Log;
import com.ztjava.core.util.ExeclUtil;
import com.ztjava.core.util.UploadUtil;
import com.ztjava.portal.Portal;
import com.ztjava.portal.model.PortalParam;
import com.ztjava.portal.model.PortalRole;
import com.ztjava.portal.model.PortalUser;
import com.ztjava.portal.model.PortalUserRole;
import com.ztjava.portal.service.PortalService;
import com.ztjava.portal.validator.LoginValidator;

public class PortalController extends BaseController{
	private static final Log log = Log.getLog(PortalController.class);
	
	//平台登录
	public void login(){
		renderBackTpl("/portal/login.html");
	}
	//验证码
	public void captcha(){
		renderCaptcha();
	}
	//平台验证
	@Before(LoginValidator.class)
	public void loginCheck(){
		String username = getPara("username");
		String password = getPara("password");
		PortalService portalService = Duang.duang(PortalService.class);
		PortalUser portalUser = portalService.getUserByUsername(username);
		if(portalUser==null){
			renderError("用户名不正确！");
			return;
		}
		if(!portalUser.getStr("password").equals(HashKit.md5(password).toUpperCase())){
			renderError("密码不正确！");
			return;
		}
		if(!portalUser.getStr("enable_flag").equals("T")){
			renderError("账号已被停用！");
			return;
		}
		setSessionAttr(Constant.BackUser, portalUser.getInt("id"));
		renderSuccess();
	}
	/***
	 * 平台首页
	 */
	@BackMethod
	public void index(){
		Integer user_id = getSessionAttr(Constant.BackUser);
		PortalUser loginUser = PortalUser.dao.findById(user_id);
		setAttr("loginUser", loginUser);
		
		PortalService portalService = Duang.duang(PortalService.class);
		//主菜单
		setAttr("leftMenuList", portalService.getUserRightsMenu("CONFIG_BACK_MENU",user_id));
		
		renderBackTpl("/portal/index.html");
	}
	
	/***
	 * 平台注销
	 */
	@BackMethod
	public void logout(){
		Integer portal_user_id = getSessionAttr(Constant.BackUser);
		removeSessionAttr(Constant.BackUser);
		CacheKit.remove(Constant.CacheCommon, "PORTAL_RIGHTS_"+portal_user_id);
		redirect("/portal/login");
	}
	/***
	 * 修改密码
	 */
	@BackMethod
	public void editPassword(){
		renderBackTpl("/portal/editPassword.html");
	}
	@BackMethod
	public void savePassword(){
		Integer portal_user_id = getSessionAttr(Constant.BackUser);
		String olderpassword = getPara("olderpassword","");
		String newpassword = getPara("newpassword","");
		String repassword = getPara("repassword","");
		if(olderpassword.equals("")||newpassword.equals("")||repassword.equals("")){
			renderError("数据不完整！");
			return;
		}
		PortalUser portalUser = PortalUser.dao.findById(portal_user_id);
		if(!portalUser.getStr("password").equals(HashKit.md5(olderpassword).toUpperCase())){
			renderError("原密码不正确！");
			return;
		}
		if(!newpassword.equals(repassword)){
			renderError("确认密码不正确！");
			return;
		}
		portalUser.set("password", HashKit.md5(newpassword).toUpperCase()).update();
		renderSuccess(true,false,"密码修改成功！");
		
	}
	/***
	 * 用户管理
	 */
	@BackMethod("PortalUser")
	public void userList(){
		if(getPara("is_ajax","F").equals("T")){
			Page<PortalUser> pd = PortalUser.dao.paginate(getParaToInt("pageNumber",1), getParaToInt("numPerPage",20),
				"select A.*", "from "+PortalUser.tablename+" A  "
				+ paramToWhere(new String[]{"username","like","A.username"},new String[]{"fullname","like","A.fullname"})
				+ orderby("A.","sortName","sortOrder"));
			databaseChange(pd.getList(), new String[]{"enable_flag","ENABLE_FLAG"});
			renderPageJson(pd);
			return;
		}
		renderBackTpl("/portal/userList.html");
	}
	
	@BackMethod("PortalUser")
	public void addEditUser(){
		Integer id = getParaToInt("id",0);
		PortalUser portalUser = new PortalUser();
		if(id>0){
			portalUser = PortalUser.dao.findById(id);
		}
		setAttr("portalUser", portalUser);
		renderBackTpl("/portal/addEditUser.html");
	}
	
	@BackMethod("PortalUser")
	public void saveUser(){
		Integer user_id = getSessionAttr(Constant.BackUser);
		PortalUser portalUser = getModel(PortalUser.class);
		PortalService portalService = Duang.duang(PortalService.class);		
		//用户名和全名不能重复		
		Ret ret = portalService.isRepeat(portalUser,PortalUser.tablename,
				new String[]{"username","String","用户名重复!"},
				new String[]{"fullname","String","全名重复！"},
				new String[]{"email","String","邮箱重复！"});
		if(ret.get("result").equals("error")){
			renderError(ret.get("message").toString());
			return;
		}
		//如果设置了密码，则进行md5加密
		if(portalUser.get("password")!=null&&!portalUser.getStr("password").equals("")){
			portalUser.set("password", HashKit.md5(portalUser.getStr("password")).toUpperCase());
		}else {
			portalUser.remove("password");
		}
		saveModel(portalUser,user_id);
		renderSuccess(true,true,"保存成功");
	}
	
	@BackMethod("PortalUser")
	public void editUserRole(){
		Integer id = getParaToInt("id");
		List<PortalRole> leftList = PortalRole.dao.find("select * from "+PortalRole.tablename+" where id not in (select role_id from "+PortalUserRole.tablename+" where user_id=?)",id);
		List<PortalRole> rightList = PortalRole.dao.find("select * from "+PortalRole.tablename+" where id in (select role_id from "+PortalUserRole.tablename+" where user_id=?)",id);
		String ids = "";
		for (int i = 0; i < rightList.size(); i++) {
			ids = ids + rightList.get(i).getInt("id");
			if(i<(rightList.size()-1)){
				ids = ids + ",";
			}
		}
		setAttr("id", id);
		setAttr("ids",ids);
		setAttr("leftList", leftList);
		setAttr("rightList", rightList);
		renderBackTpl("/portal/editUserRole.html");
	}

	@BackMethod("PortalUser")
	public void saveUserRole(){
		Integer id = getParaToInt("id");
		String ids = getPara("ids","");
		Db.update("delete from "+PortalUserRole.tablename+" where user_id=?",id);
		if(!ids.equals("")){
			String[] arr = ids.split(",");
			for(int i=0;i<arr.length;i++){
				PortalUserRole item = new PortalUserRole();
				item.set("user_id", id);
				item.set("role_id", Integer.parseInt(arr[i]));
				item.save();
			}
		}
		renderSuccess(true,false, "保存成功！");
	}
	
	/***
	* PortalRole
	* @AutoCode 2016-07-02 17:23:02
	*/
	@BackMethod("PortalRole")
	public void roleList(){
		if(getPara("is_ajax","F").equals("T")){
			Page<PortalRole> pd = PortalRole.dao.paginate(getParaToInt("pageNumber",1), getParaToInt("numPerPage",20),
					"select *", "from "+PortalRole.tablename
					+ paramToWhere(new String[]{"name",w_like})
					+ orderby("","sortName","sortOrder"));
			renderPageJson(pd);
			return;	
		}
		renderBackTpl("/portal/roleList.html");
	}

	@BackMethod("PortalRole")
	public void addEditRole(){
		Integer id = getParaToInt("id",0);
		PortalRole portalRole = new PortalRole();
		List<Record> rightsList = CacheKit.get(Constant.CacheData, "CONFIG_BACK_MENU");
		if(id>0){
			portalRole = PortalRole.dao.findById(id);
			if(portalRole.get("rights")!=null){
				recordChecked(rightsList,portalRole.getStr("rights"));
			}
		}
		setAttr("portalRole", portalRole);
		setAttr("rightsJSON", JsonKit.toJson(rightsList));
		renderBackTpl("/portal/addEditRole.html");
	}
	private void recordChecked(List<Record> list,String str){
		for(int i=0;i<list.size();i++){
			if((","+str+",").indexOf(","+list.get(i).getStr("rights")+",")>-1){
				list.get(i).set("checked", true);
				if(list.get(i).get("children")!=null){
					recordChecked((List<Record>)list.get(i).get("children"),str);
				}
			}
		}
	}

	@BackMethod("PortalRole")
	public void saveRole(){
		Integer user_id = getSessionAttr(Constant.BackUser);
		PortalRole portalRole = getModel(PortalRole.class);
		
		PortalService portalService = Duang.duang(PortalService.class);		
		if(portalService.isRepeat(portalRole,PortalRole.tablename,"name")){
			renderError("角色名称不能重复");
			return;
		}
		saveModel(portalRole,user_id);
		renderSuccess(true,true,"保存成功");
	}

	@BackMethod("PortalRole")
	public void batchDeleteRole(){
		String[] ids = getParaValues("ids");
		PortalService portalService = Duang.duang(PortalService.class);
		portalService.batchDelete(PortalRole.tablename, ids);
		renderSuccess();
	}

	@BackMethod("PortalParam")
	public void paramList(){
		Map<String,Record> paramMap = new LinkedHashMap<String,Record>();
		List<String> list = CacheKit.getKeys(Constant.CacheParam);
		for(int i=0;i<list.size();i++){
			paramMap.put(list.get(i),(Record)CacheKit.get(Constant.CacheParam, list.get(i)));
		}
		setAttr("paramMap", paramMap);
		renderBackTpl("/portal/paramList.html");
	}
	@BackMethod("PortalParam")
	public void saveParam(){
		Integer user_id = getSessionAttr(Constant.BackUser);
		List<String> list = CacheKit.getKeys(Constant.CacheParam);
		for(int i=0;i<list.size();i++){
			Record record = CacheKit.get(Constant.CacheParam, list.get(i));
			if(!getPara(list.get(i)).equals(record.getStr("value"))){				
				PortalParam portalParam = new PortalParam();
				portalParam.set("id", record.get("id"));
				portalParam.set("name", record.get("name"));
				portalParam.set("value", getPara(list.get(i)));
				portalParam.set("code", record.get("code"));
				portalParam.set("remark", record.get("remark"));
				saveModel(portalParam, user_id);
				
				record.set("id", portalParam.get("id"));
				record.set("value", getPara(list.get(i)));
				CacheKit.put(Constant.CacheParam, list.get(i), record);
			}
		}
		renderSuccess();
	}
	
	//用于后台各个模块上传图片使用
	@BackMethod
	public void uploader(){
		keepPara();
		renderBackTpl("/portal/uploader.html");
	}
	@BackMethod
	public void doUploader(){
		Integer user_id = getSessionAttr(Constant.BackUser);
		String path = null;
		try{
			path = UploadUtil.upload(this, user_id);
		}catch (Exception e) {
			e.printStackTrace();
			log.error("文件上传失败");
		}
		if(path==null){
			 renderText("{\"err\":\"上传出错！\"}");
			 return;
		}
		renderText("{\"result\":\"success\",\"message\" :\"上传成功！\",\"savepath\":\""+path+"\"}");
	}

	public void xheditorUpload(){
		Integer user_id = getSessionAttr(Constant.BackUser);
		String result = null;
		try{
			result = UploadUtil.upload(this, user_id);
		}catch (Exception e) {
			e.printStackTrace();
			log.error(e.getMessage());
		}
		if(result==null){
            renderText("{\"err\":\"上传出错！\"}");
            return;
		}
		renderText("{\"err\":\"\",\"msg\":{\"url\":\""+result+"\"}}");
	}
	
	@BackMethod
	public void clearCache(){
		CacheKit.removeAll(Constant.CacheAutoClear);
		
		//必须分开，以便覆盖配置
		for(String key:Constant.pluginObject.keySet()){
			InitConfig.loadPluginConfig(Constant.pluginPackage.get(key),key);
		}
		//可进行项目级别自定义参数，覆盖各插件参数
		InitConfig.loadAllConfig("config.json");
		for(String key:Constant.pluginObject.keySet()){
			Constant.pluginObject.get(key).afterJFinalStart();
		}
		renderSuccess("清理完成！");
	}
	//为后台各模块提供简单execl上传功能
	@BackMethod
	public void saveImportExecl() throws Exception{
		UploadFile uploadFile = getFile("file");
		Integer user_id = getSessionAttr(Constant.BackUser);
		Ret result = ExeclUtil.execlToList(uploadFile, getPara("importCode",""), getPara("basedate",""), user_id,getPara("repeat","notice"), "");
		if(result.get("result").equals("error")){
			renderError(result.get("message").toString());
			return;
		}
		Record improtConfig = CacheKit.get(Constant.CacheData,  getPara("code",""));
		Db.batchSave(improtConfig.getStr("tablename"),(List<Record>)result.get("list"),improtConfig.getInt("perSize"));
		renderSuccess(true, true, "导入："+result.get("success_num")+"条，跳过："+result.get("continue_num")+"条！");
	}
}
